package com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.proof.face

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.http.hitPointCameroon
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.facedoing.FaceCameroonDoingActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.subview.HotlineCameroonDialog
import com.helasasa.maxfunds.lineofcredit.cashloan.databinding.ActivityCameroonProofFaceBinding
import com.vmadalin.easypermissions.EasyPermissions
import com.vmadalin.easypermissions.dialogs.DEFAULT_SETTINGS_REQ_CODE
import com.vmadalin.easypermissions.dialogs.SettingsDialog

class ProofCameroonFaceActivity : AppCompatActivity(), EasyPermissions.PermissionCallbacks,
    EasyPermissions.RationaleCallbacks {

    private lateinit var proofFaceViewModel: ProofCameroonFaceViewModel
    private lateinit var binding: ActivityCameroonProofFaceBinding

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 数据模型
        proofFaceViewModel = ViewModelProvider(this)[ProofCameroonFaceViewModel::class.java]

        // 关联布局
        binding = ActivityCameroonProofFaceBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 用到的控件
        val hotline = binding.navbarRight
        val back = binding.navbarLeft
        val save = binding.save
        val loading = binding.loading

        // 页面loading状态接口监听
        proofFaceViewModel.loadingResult.observe(this@ProofCameroonFaceActivity, Observer {
            val loadingResult = it ?: return@Observer

            if (loadingResult) {
                loading.visibility = View.VISIBLE
            } else {
                loading.visibility = View.GONE
            }
        })

        // 页面UI状态接口监听
        proofFaceViewModel.pageDetailResult.observe(this@ProofCameroonFaceActivity, Observer {
            val pageDetailResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (pageDetailResult.startFaceDetect == true) {
                binding.face.performClick()
                return@Observer
            }

            selectType(
                pageDetailResult.facePicBitmap,
                pageDetailResult.facePicUrl
            )
        })

        // 流程接口监听
        proofFaceViewModel.mainProcessResult.observe(this@ProofCameroonFaceActivity, Observer {
            val mainProcessResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (mainProcessResult.error != null) {
                showMessage(mainProcessResult.error)
            }

            if (mainProcessResult.success != null) {
                proofFaceViewModel.nextRouter(mainProcessResult.success)
            }
        })

        // 页面需要跳转监听
        proofFaceViewModel.nextRouterResult.observe(this@ProofCameroonFaceActivity, Observer {
            val nextRouterResult = it ?: return@Observer

            loading.visibility = View.GONE
            startNextActivity(nextRouterResult.nextPage)
        })

        // 点击保存
        save.setOnClickListener {
            if (askCameraPermission()) return@setOnClickListener

            proofFaceViewModel.startFaceDetecting()
            hitPointCameroon("PROOF_FACE_COMMIT")
        }

        // 点击客服
        hotline.setOnClickListener {
            // 客服弹框
            HotlineCameroonDialog().showNow(supportFragmentManager, "hotline")
            hitPointCameroon("SHOW_HOTLINE")
        }

        // 点击返回
        back.setOnClickListener {
            finish()
        }

        // 点击face
        binding.face.setOnClickListener {
            if (askCameraPermission()) return@setOnClickListener

            val intent =
                Intent(this@ProofCameroonFaceActivity, FaceCameroonDoingActivity::class.java)
            startActivityForResult(intent, REQUEST_CODE_ACTIVITY_FACE_DOING)

            hitPointCameroon("PROOF_FACE_START_CLICK")
        }
        binding.result.setOnClickListener {
            if (askCameraPermission()) return@setOnClickListener

            val intent =
                Intent(this@ProofCameroonFaceActivity, FaceCameroonDoingActivity::class.java)
            startActivityForResult(intent, REQUEST_CODE_ACTIVITY_FACE_DOING)

            hitPointCameroon("PROOF_FACE_START_CLICK")
        }
    }

    /**
     * 更新类型选择UI
     */
    @SuppressLint("SetTextI18n")
    private fun selectType(frontBitmap: Bitmap? = null, frontUrl: String? = null) {
        // 更新占位图
        if (frontBitmap != null) {
            binding.face.visibility = View.GONE
            binding.resultBg.visibility = View.VISIBLE
            binding.result.setImageBitmap(frontBitmap)
        } else {
            binding.face.visibility = View.VISIBLE
            binding.resultBg.visibility = View.GONE
        }

        if (frontUrl.isNullOrBlank()) {
            binding.save.text = "Commencer à prendre un selfie"
        } else {
            binding.save.text = "Confirmer et soumettre"
        }
    }

    /**
     * 请求相机权限
     */
    private fun askCameraPermission(): Boolean {
        val list = mutableListOf(android.Manifest.permission.CAMERA)
        if (checkPermissionsGranted(list)) {
            return false
        }
        // 未同意权限
        EasyPermissions.requestPermissions(
            this,
            "App will request Camera Permission",
            100,
            *(list.toTypedArray())
        )
        return true
    }

    /**
     * 检查权限是否同意
     */
    private fun checkPermissionsGranted(permissionList: List<String>): Boolean {
        val isNotAllGranted = permissionList.any {
            PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, it)
        }
        return !isNotAllGranted
    }

    // ------> EasyPermissions <------
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onRationaleAccepted(requestCode: Int) {
        askCameraPermission()
    }

    override fun onRationaleDenied(requestCode: Int) {
    }

    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            SettingsDialog.Builder(this).build().show()
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == DEFAULT_SETTINGS_REQ_CODE) {
            askCameraPermission()
        } else if (requestCode == REQUEST_CODE_ACTIVITY_FACE_DOING) {
            if (resultCode == RESULT_OK) {
                val imageOutputPath = data?.getStringExtra("imageOutputPath")
                // 更新页面
                proofFaceViewModel.handleTakePictureResult(imageOutputPath)
            }
        }
    }

    override fun onResume() {
        super.onResume()
        hitPointCameroon(type = this::class.java.simpleName, isPageStart = true)
    }

    override fun onPause() {
        super.onPause()
        hitPointCameroon(type = this::class.java.simpleName, isPageEnd = true)
    }
}

fun Context.showMessage(message: String) {
    Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()
}

fun Context.startNextActivity(
    activity: Class<out AppCompatActivity>? = null,
    params: HashMap<String, String> = HashMap()
) {
    val nextActivity = activity ?: return
    try {
        val intent = Intent(this, nextActivity)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
        params.keys.forEach { gKey ->
            intent.putExtra(gKey, params[gKey])
        }
        startActivity(intent)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}